package com.cd.javacxy.common.interceptor;

import com.cd.javacxy.common.annotation.RequireLogin;
import com.cd.javacxy.common.model.enums.ResponseCode;
import com.cd.javacxy.common.model.vo.AjaxResponse;
import com.cd.javacxy.common.utils.Constants;
import com.cd.javacxy.common.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器，拦截{@link com.cd.javacxy.common.annotation.RequireLogin}
 *
 * @author yanghy
 * @version V1.0
 * @date 2019/11/9
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断如果不是请求control方法直接返回true
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        //判断访问的control是否添加LoginRequired注解
        RequireLogin requireLogin = method.getMethodAnnotation(RequireLogin.class);
        if (requireLogin != null) {
            HttpSession session = request.getSession();
            //判断session中有没有user信息
            if (session.getAttribute(Constants.SESSION_USER_KEY) == null) {
                log.info("未登录用户");
                final String xmlHttpRequest = "XMLHttpRequest";
                final String requestedWith = "X-Requested-With";
                if (xmlHttpRequest.equalsIgnoreCase(request.getHeader(requestedWith))) {
                    AjaxResponse<Object> re = AjaxResponse.builder().code(ResponseCode.LOGINTIMEOUT.getCode()).errorMsg("未登录用户").build();
                    ResponseUtil.writeJavaScript(re, response);
                } else {
                    //没有user信息的话进行路由重定向
                    response.sendRedirect("/signin");
                }
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
